package com.chunxuan.langquan.support.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BaseWebView extends WebView {
    private Context context;

    public BaseWebView(Context context) {
        this(context, null);
        this.context=context;
        init();

    }

    public BaseWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        init();
    }

    public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);//解决webview无法弹出软键盘，defstyleattr 不能传0
        this.context = context;
        init();
    }

    private void init() {
        WebSettings webSettings = this.getSettings();
        //支持js
        webSettings.setJavaScriptEnabled(true);
        //开启DOM storage API功能
        webSettings.setDomStorageEnabled(true);
        //webSettings.setPluginState(WebSettings.PluginState.ON);
        //设置缓存方式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //设置下载
//        setDownloadListener(new MyDownloadListener());
        //将图片调整到适合webView的大小
        webSettings.setUseWideViewPort(true);
        //支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(false);
        //支持内容重新布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webSettings.setUserAgentString(System.getProperty("http.agent"));
        webSettings.setAppCacheEnabled(true);
        //多窗口
        //webSettings.supportMultipleWindows();
        //当调用requestFocus时为webView设置节点
        webSettings.setNeedInitialFocus(true);
        //设置可以访问文件
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        //设置支持缩放
//        webSettings.setBuiltInZoomControls(true);
        //支持js打开新窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //缩放至屏幕大小
        webSettings.setLoadWithOverviewMode(true);
        //1.加快html加载进度
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }

        this.setWebViewClient(new BaseWebViewClient());
        this.setWebChromeClient(new WebChromeClient());
    }

    //辅助WebView处理各种通知，请求等事件
    //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
    private class BaseWebViewClient extends WebViewClient {


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            //开始加载网页时处理



        }

        @Override
        public void onPageFinished(WebView view, String url) {
            //super.onPageFinished(view, url);
            //2.加快html加载进度
            if (!view.getSettings().getLoadsImagesAutomatically()) {
                view.getSettings().setLoadsImagesAutomatically(true);
            }
            //网页加载完成时处理
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListner(view);
        }


        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            //网页加载失败时处理

            Log.e("abc", "onReceivedError: ======>>>"+error );

        }

        //处理https请求
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //super.onReceivedSslError(view, handler, error);
            handler.proceed();//接受信任所有网站的证书
            //handler.cancel();//默认操作，不作处理
            handler.handleMessage(null);//可做其他处理
        }




    }




    // 注入js函数监听
    private void addImageClickListner(WebView view) {
        //遍历页面中所有img的节点，因为节点里面的图片的url即objs[i].src，保存所有图片的src.
        //为每个图片设置点击事件，objs[i].onclick
        view.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{" +
                "window.imagelistner.readImageUrl(objs[i].src);  " +
                " objs[i].οnclick=function()  " +
                " {  " +
                " window.imagelistner.openImage(this.src);  " +
                "  }  " +
                "}" +
                "})()");
    }


    //辅助WebView处理javascript的对话框、网站图标、网页标题及网页加载进度等
    private class BaseWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

    }

    class MyDownloadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
            Uri uri = Uri.parse(s);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        }
    }

    //返回上一次浏览
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack()) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
